
<template>
  <div>
    <!-- 处方信息框 -->
    <div class="patient-container">
      <div class="patient-info">
        <h1>
          <strong>处方信息</strong>
          <span style="float: right; ">
            <el-button type="primary" @click="confirmAddPrescription">保 存</el-button>
            <el-button @click="cancel">取 消</el-button>
          </span>
        </h1>
        <!-- 开具处方 -->
        <el-form :title="title" v-model="open" width="500px" append-to-body>
          <el-form ref="form" :model="form" :rules="rules" label-width="80px">
            <el-form-item label="开具日期" prop="createDate">
              <el-date-picker clearable
                              v-model="form.createDate"
                              type="date"
                              format="YYYY-MM-DD"
                              value-format="YYYY-MM-DD"
                              placeholder="请选择开具日期">
              </el-date-picker>
            </el-form-item>
            <el-form-item label="付数" prop="count">
              <el-input v-model="form.count" placeholder="请输入付数" />
            </el-form-item>
            <el-form-item label="病历号" prop="medicalRecordId">
              <el-input readonly v-model="form.medicalRecordId" placeholder="请选择病历" id="recordIdInput" style="width: 50%;float: left;" />
              <span>
                <el-button style="margin-top: 0;margin-left: 50%;" type="primary" class="sel_rec_btn" @click="selectRecord">选择病历</el-button>
              </span>
            </el-form-item>
            <el-form-item label="疗法" prop="therapy">
              <el-input v-model="form.therapy" placeholder="请输入疗法" />
            </el-form-item>
            <el-form-item label="详情" prop="therapyDetails">
              <el-input type="textarea" v-model="form.therapyDetails" placeholder="请输入详情" />
            </el-form-item>
            <el-form-item label="医疗建议" prop="medicalAdvice">
              <el-input type="textarea" v-model="form.medicalAdvice" placeholder="请输入医疗建议" />
            </el-form-item>
            <el-form-item label="用药频率" prop="frequency">
              <el-input v-model="form.frequency" placeholder="请输入用药频率" />
            </el-form-item>
            <el-form-item label="用法用量" prop="usageMeans">
              <el-input v-model="form.usageMeans" placeholder="请输入用法用量" />
            </el-form-item>
            <el-form-item label="备注" prop="remark">
              <el-input v-model="form.remark" placeholder="请输入备注" />
            </el-form-item>
          </el-form>
        </el-form>
        <div >

        </div>
      </div>
    </div>

    <!-- 选择药品界面 -->
    <div class="drug-container">
      <h1><strong>选择药品</strong></h1>
      <el-divider></el-divider>
      <div class="drug-select">
        <el-form :model="drugParams" ref="queryForm" :inline="true" v-show="showSearch" label-width="68px">
          <el-form-item style="margin-left: 20px;" label="药品名称" prop="name">
            <el-input

                v-model="drugParams.name"
                placeholder="请输入药品名称"
                clearable
                @keyup.enter.native="handleQuery"
            />
          </el-form-item>
          <el-form-item style="margin-left: 20px;" label="通用名称" prop="genericName">
            <el-input
                v-model="drugParams.genericName"
                placeholder="请输入通用名称"
                clearable
                @keyup.enter.native="handleQuery"
            />
          </el-form-item>
          <el-form-item style="float: right">
            <el-button type="primary" icon="el-icon-search" size="mini" @click="getDrugs">搜索</el-button>
            <el-button icon="el-icon-refresh" size="mini" @click="resetDrugQuery">重置</el-button>
          </el-form-item>
        </el-form>

        <!-- 显示药品信息 -->
        <el-table v-loading="loading" :data="drugList"
                  max-height="200px"
                  @selection-change="handleSelectionChange">
          <el-table-column label="药品编号" align="center" prop="code" />
          <el-table-column label="名称" align="center" prop="name" />
          <el-table-column label="通用名称" align="center" prop="genericName" />
          <el-table-column label="规格" align="center" prop="specification" />
          <el-table-column label="单价" align="center" prop="price" />
          <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
            <template #default="scope">
              <el-button type="primary" @click="selectedDrug(scope.row)">选择</el-button>
            </template>

          </el-table-column>
        </el-table>
          <pagination
              v-show="total>0"
              :total="total"
              :page.sync="queryParams.pageNum"
              :limit.sync="queryParams.pageSize"
              @pagination="getDrugs"
          />
      </div>
    </div>

    <!-- 已选药品 -->
    <div>
      <el-table id="selectedDrugs" class="selected-drug" v-loading="loading" :data="selectedDrugList">
        <el-table-column label="药品编号" align="center" prop="code" />
        <el-table-column label="名称" align="center" prop="name" />
        <el-table-column label="通用名称" align="center" prop="genericName" />
        <el-table-column label="规格" align="center" prop="specification" />
        <el-table-column label="制造商" align="center" prop="manufacturer" />
        <el-table-column label="批准文号" align="center" prop="approvalNumber" />
        <el-table-column label="适应症" align="center" prop="disease" />
        <el-table-column label="单价" align="center" prop="price" />
        <el-table-column label="剂型" align="center" prop="dosageForm" />
        <el-table-column label="分类" align="center" prop="type" />

        <el-table-column label="数量" align="center" width="200px" prop="count">
          <template #default="scope">
            <el-input-number v-model="scope.row.count" :min="1" :max="10" label="数量"/>
          </template>
        </el-table-column>
        <el-table-column label="操作" align="center">
          <template #default="scope">
            <el-button type="primary" @click="dropSelectedDrug(scope.$index)">
              退药
            </el-button>
          </template>

        </el-table-column>
      </el-table>

    </div>

    <!-- 选择病历对话框 -->
    <el-dialog :title="title" v-model="open" width="1000px" append-to-body>
      <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
        <el-form-item label="病历号" prop="number">
          <el-input
              v-model="queryParams.number"
              placeholder="请输入病历号"
              clearable
              @keyup.enter.native="handleQuery"
          />
        </el-form-item>
        <el-form-item label="患者姓名" prop="patientId">
          <el-input
              v-model="queryParams.patientName"
              placeholder="请输入患者姓名"
              clearable
              @keyup.enter.native="handleQuery"
          />
        </el-form-item>
        <el-form-item label="医生编号" prop="doctorId">
          <el-input
              v-model="queryParams.doctorId"
              placeholder="请输入医生编号"
              clearable
              @keyup.enter.native="handleQuery"
          />
        </el-form-item>
        <el-form-item label="医生姓名" prop="doctorName">
          <el-input
              v-model="queryParams.doctorName"
              placeholder="请输入医生姓名"
              clearable
              @keyup.enter.native="handleQuery"
          />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
          <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
        </el-form-item>
      </el-form>
      <el-table
          height="400"
          v-loading="loading"
          :data="recordInfoList"
          @selection-change="handleSelectionChange"
          stripe border
          row-key="number"
          ref="recordInfo">
        <el-table-column label="病历号" align="center" prop="number" />
        <el-table-column label="患者姓名" align="center" prop="patientName" />
        <el-table-column label="医生编号" align="center" prop="doctorId" />
        <el-table-column label="医生姓名" align="center" prop="doctorName" />
        <el-table-column label="会诊日期" align="center" prop="date" width="180">
          <template v-slot="{ row }">
            <span>{{ parseTime(row.date, '{y}-{m}-{d}') }}</span>
          </template>
        </el-table-column>
        <el-table-column type="selection" width="55" align="center" />

      </el-table>
      <div>
        <el-button style="margin-left: 93%;margin-top: 20px" type="primary" @click="confirmRecord">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listPrescription, getPrescription, addPrescription, updatePrescription } from "@/api/emr/add_prescription";

import { listRecordInfo, addDrugToPrescription } from "@/api/emr/add_prescription"
import { listDrug } from "@/api/emr/drug";


export default {
  name: "Add_prescription",
  data() {
    return {
      // 遮罩层
      loading: false,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 开具处方表格数据
      add_prescriptionList: [],
      // 药品项目表格数据
      drugList: [],
      // 已选药品表格数据
      selectedDrugList: [],
      // 处方关联任务数据
      recordInfoList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      drugParams:{
        pageNum: 1,
        pageSize: 10,
        code: null,
        name: null,
        genericName: null,
        specification: null,
        manufacturer: null,
        approvalNumber: null,
        createDate: null,
        expirationDate: null,
        storageConditions: null,
        disease: null,
        price: null,
        dosageForm: null,
        type: null,
        ingredients: null,
        stock: null,
        status: null,
        usageInstructions: null
      },
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        id: null,
        number: null,
        patientName: null,
        doctorId: null,
        doctorName: null,
        date: null,
      },
      // 表单参数
      form: {
        createDate: null,
        count: null,
        medicalRecordId: null,
        amount: null,
        therapy: null,
        therapyDetails: null,
        medicalAdvice: null,
        frequency: null,
        usageMeans: null,
        remark: null,
      },
      /** 处方所含药物表单 */
      formPrescriptionAndDrug: {
        prescriptionId: null,
        drugId: null,
        count: null,
      },
      // 表单校验
      rules: {
        createDate:[
          { required: true, message: "日期不能为空", trigger: "blur" }
        ],
        medicalRecordId: [
          { required: true, message: "病历号不能为空", trigger: "blur" }
        ],
        count: [
          { required: true, message: "付数不能为空", trigger: "blur" }
        ],
        therapy: [
          { required: true, message: "疗法不能为空", trigger: "blur" }
        ],
        therapyDetails: [
          { required: true, message: "疗法细节不能为空", trigger: "blur" }
        ],
        medicalAdvice: [
          { required: true, message: "医疗建议不能为空", trigger: "blur" }
        ],
        frequency: [
          { required: true, message: "用药频率不能为空", trigger: "blur" }
        ],
        usageMeans: [
          { required: true, message: "用法用量不能为空", trigger: "blur" }
        ],
      },
      //选中的病历行
      selectedRow: [],
      //选中的病历号
      selectedRecordId: 0,
      //最近生成的处方信息，用于添加药物与处方的关联表
      latestPrescriptionId: 0
    };
  },
  created() {
    this.getRecord();
    this.getDrugs();
    this.reset();
  },
  methods: {
    /** 选择药品 */
    selectedDrug(row) {
      row.count = 1;
      this.selectedDrugList.push(row);
    },
    /** 退选药品 */
    dropSelectedDrug(index) {
      this.selectedDrugList.splice(index, 1);
    },
    /** 查询所有病历信息 */
    getRecord() {
      this.loading = true;
      listRecordInfo(this.queryParams).then(response => {
        this.recordInfoList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    /** 查询药品项目列表 */
    getDrugs() {
      this.loading = true;
      listDrug(this.drugParams).then(response => {
        this.drugList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    /** 确认添加处方 */
    confirmAddPrescription() {
      let totalPrice = 0;
      for(let i = 0; i < this.selectedDrugList.length; i++) {
        totalPrice += this.selectedDrugList[i].price * this.selectedDrugList[i].count;
      }
      this.form.amount = totalPrice;
      this.$refs["form"].validate(valid => {
        if (valid) {
            addPrescription(this.form).then(response => {
              this.formPrescriptionAndDrug.prescriptionId = response.data.id;

              for(let i = 0; i < this.selectedDrugList.length; i++) {
                this.formPrescriptionAndDrug.drugId = this.selectedDrugList[i].id;
                this.formPrescriptionAndDrug.count = this.selectedDrugList[i].count;
                addDrugToPrescription(this.formPrescriptionAndDrug).then(response => {
                  if (i === this.selectedDrugList.length-1) {
                    this.$modal.msgSuccess("保存成功");
                    //this.reset();
                    //window.location.href="/emr/prescription";
                  }
                });
              }
            });
          }
      });

    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        status: null,
        createDate: null,
        count: null,
        medicalRecordId: null,
        amount: null,
        therapy: null,
        therapyDetails: null,
        medicalAdvice: null,
        frequency: null,
        usageMeans: null,
        type: null,
        createBy: null,
        createTime: null,
        updateBy: null,
        updateTime: null,
        remark: null
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.getRecord();
    },
    /** 选择病历按钮操作 */
    selectRecord() {
      this.open = true
      this.title = "选择病历"
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    /** 重置药物查询操作 */
    resetDrugQuery(){
      this.drugParams = {
          pageNum: 1,
          pageSize: 10,
          code: null,
          name: null,
          genericName: null,
          specification: null,
          manufacturer: null,
          approvalNumber: null,
          createDate: null,
          expirationDate: null,
          storageConditions: null,
          disease: null,
          price: null,
          dosageForm: null,
          type: null,
          ingredients: null,
          stock: null,
          status: null,
          usageInstructions: null
        };
      this.getDrugs();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.selectedRow = selection
      if (selection.length > 1) {
        this.$refs.recordInfo.clearSelection();
        this.$refs.recordInfo.toggleRowSelection(selection.pop());
      }
      if (selection.length !== 0) {
        this.selectedRecordId = selection[selection.length-1].number
      }
    },
    //确认选择的病历号
    confirmRecord() {
      let inputElement = document.getElementById("recordIdInput");
      inputElement.value = this.selectedRecordId;
      this.form.medicalRecordId = this.selectedRecordId;
      this.open = false;
    },
  }
};
</script>
